package com.csdig.cms.directive;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.csdig.cms.model.ext.ContentExt;
import com.csdig.cms.service.ContentService;
import com.csdig.cms.utils.DirectiveUtils;
import com.csdig.cms.utils.FrontUtils;
import com.csdig.cms.web.URLHelper;
import com.csdig.db.model.Pagination;

import freemarker.core.Environment;
import freemarker.template.ObjectWrapper;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

@Service("contentPagDirective")
public class ContentPageDirective implements TemplateDirectiveModel {

	/**
	 * 输入参数，文章ID。允许多个文章ID，用","分开。排斥其他所有筛选参数。
	 */
	public static final String CHANNEL_ID = "channel_id";

	public static final String ORDER_BY = "orderBy";

	@SuppressWarnings("unchecked")
	@Override
	public void execute(Environment env, @SuppressWarnings("rawtypes") Map params, TemplateModel[] loopVars,
			TemplateDirectiveBody body) throws TemplateException, IOException {

		TemplateModel reqUri = env.getVariable(FrontUtils.REQ_URI);
		int pageNo = URLHelper.getPageNo(reqUri.toString());
		Integer channelIds = DirectiveUtils.getInt(CHANNEL_ID, params);
		String orderBy = DirectiveUtils.getString(ORDER_BY, params);
		// 每页10条
		Pagination<ContentExt> pag = null;

		try {
			pag = contentService.getPagByIdsForTag(channelIds, pageNo, orderBy);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(DirectiveUtils.OUT_PAG, ObjectWrapper.DEFAULT_WRAPPER.wrap(pag));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

	@Autowired
	private ContentService contentService;

}
